package com.area.cth.service.impl;

import com.area.cth.pojo.Message;
import com.area.cth.pojo.User;
import com.area.cth.utils.ThreadLocalUtil;
import com.area.cth.vo.MessageVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.area.cth.service.MessageService;
import com.area.cth.mapper.MessageMapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 1
 * @description 针对表【message】的数据库操作Service实现
 * @createDate 2024-12-19 15:28:27
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
        implements MessageService {

    @Override
    public List<Message> findAllMessageById(Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer personId = (Integer) map.get("id");
        List<Message> list = lambdaQuery()
                .in(Message::getSendUser, personId, id)
                .in(Message::getReceiveUser, personId, id)
                .orderByAsc(Message::getCreateTime)
                .list();
        return list;
    }

    //获取最新消息列表
    @Override
    public List<MessageVO> findAllMessage() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer personId = (Integer) map.get("id");
        List<Message> list = lambdaQuery()
                .eq(Message::getSendUser, personId)
                .or()
                .eq(Message::getReceiveUser, personId)
                .list();
        Set<Integer> set = new HashSet<>();
        list.forEach(i -> {
            set.add(i.getSendUser());
            set.add(i.getReceiveUser());
        });
        set.remove(personId);
        List<MessageVO> listVO = new ArrayList<>();
        set.forEach(i -> {
            Message m = lambdaQuery()
                    .in(Message::getSendUser, personId, i)
                    .in(Message::getReceiveUser, personId, i)
                    .orderByDesc(Message::getCreateTime)
                    .last("limit 1")
                    .one();
            MessageVO vo = new MessageVO();
            BeanUtils.copyProperties(m, vo);
            vo.setTargetUser(i);
            User u = Db.lambdaQuery(User.class)
                    .select(User::getUsername, User::getNickname, User::getAvatar)
                    .eq(User::getId, i)
                    .one();
            BeanUtils.copyProperties(u, vo);
            vo.setCreateTime(m.getCreateTime());
            listVO.add(vo);
        });
        System.out.println(listVO);
        return listVO;
    }
}




